package org.langqiao.io.file;

import java.io.File;
import java.io.IOException;

public class FileUtil {

	public static void main(String[] args) {
		try {
			System.out.println(getCurrentDir());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取当前文件所在的绝对路径
	 * @return String
	 */
	public static String getCurrentDir() throws IOException{
		File directory = new File(".");
		File newPath = null;
		try {
			newPath = new File(directory.getCanonicalPath());
			newPath.mkdir();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(newPath != null){
			return newPath.getPath() + File.separator;
		}else{
			return File.separator;
		}		
	}
	
	/**  
     * 获取当前项目的根目录
     * @return String
     */  
    public static String getRootPath(){   
    	
        String result = FileUtil.class.getResource("FileUtil.class").toString();   
        int index = result.indexOf("WEB-INF");   
        if(index == -1){   
            index = result.indexOf("bin");   
        }   
        result = result.substring(0,index);   
        if(result.startsWith("jar")){   
            // 当class文件在jar文件中时，返回"jar:file:/F:/ ..."样的路径    
            result = result.substring(10);   
        }else if(result.startsWith("file")){   
            // 当class文件在class文件中时，返回"file:/F:/ ..."样的路径    
            result = result.substring(6);   
        }   
        if(result.endsWith("/"))
        	//不包含最后的"/"   
        	result = result.substring(0,result.length()-1);
        return result;   
    }   
}
